package com.xingchi.unique.service.impl;

import com.xingchi.common.unique.GeneratorType;
import com.xingchi.unique.config.UniqueProperties;
import com.xingchi.unique.factory.RedisIdFactory;
import com.xingchi.unique.factory.SnowflakeFactory;
import com.xingchi.unique.factory.UUIDFactory;
import com.xingchi.unique.service.IDGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * id生成服务实现
 *
 * @author xingchi
 * @date 2023/3/10 20:06
 * @modified xingchi
 */
@Service
@SuppressWarnings("all")
public class IDGeneratorServiceImpl implements IDGeneratorService {


    @Autowired
    private SnowflakeFactory snowflakeFactory;

    @Autowired
    private UUIDFactory uuidFactory;

    @Autowired
    private RedisIdFactory redisIdFactory;

    @Autowired
    private UniqueProperties uniqueProperties;

    @Override
    public Long snowflakeId() {
        return snowflakeFactory.nextId();
    }

    @Override
    public List<Long> snowflakeIds(Integer count) {

        if (count == null || count <= 0) {
            count = 10;
        }

        return snowflakeFactory.nextIds(count);
    }

    @Override
    public String uuid(boolean removeLine) {
        return uuidFactory.nextId();
    }

    @Override
    public Long redisId() {
        UniqueProperties.RedisId redisId = uniqueProperties.getRedisId();
        return redisIdFactory.nextId(redisId.getBusinessPrefix());
    }

    @Override
    public List<Long> redisIds(Integer count) {

        if (count == null || count <= 0) {
            count = 10;
        }
        UniqueProperties.RedisId redisId = uniqueProperties.getRedisId();
        return redisIdFactory.nextIds(redisId.getBusinessPrefix(), count);
    }

    @Override
    public String uniqueId(GeneratorType generatorType) {
        String result = null;
        switch (generatorType) {
            case UUID:
                result = this.uuid(true);
                break;
            case REDIS:
                result = String.valueOf(this.redisId());
                break;
            case SNOWFLAKE:
                result = String.valueOf(this.snowflakeId());
                break;
            default:
                // 默认使用兜底方法
                result = String.valueOf(this.snowflakeId());
        }

        return result;
    }

    @Override
    public List<String> uniqueIds(GeneratorType generatorType, int count) {

        List<String> result = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            result.add(this.uniqueId(generatorType));
        }
        return result;
    }
}
